package com.lv.dhart.ui.activity.login;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.StringRes;
import androidx.lifecycle.ViewModelProvider;

import com.lv.dhart.BaseActivity;
import com.lv.dhart.R;
import com.lv.dhart.api.bean.LoginSendCodeBean;
import com.lv.dhart.beans.login.LoginBean;
import com.lv.dhart.callback.ILoginCallback;
import com.lv.dhart.callback.ISMSCodeCallback;
import com.lv.dhart.constant.AppConstant;
import com.lv.dhart.constant.ComParamContact;
import com.lv.dhart.databinding.ActivityLoginBinding;
import com.lv.dhart.http.rxeasy.EasyHttp;
import com.lv.dhart.http.rxeasy.callback.ProgressDialogCallBack;
import com.lv.dhart.http.rxeasy.exception.ApiException;
import com.lv.dhart.http.rxeasy.subsciber.IProgressDialog;
import com.lv.dhart.model.AuthModel;
import com.lv.dhart.model.LoginCache;
import com.lv.dhart.presenter.LoginPresenter;
import com.lv.dhart.token.TokenManager;
import com.lv.dhart.ui.activity.BottomBarActivity;
import com.lv.dhart.utilcode.util.SPStaticUtils;
import com.lv.dhart.utilcode.util.ToastUtils;
import com.lv.dhart.utils.MD5;
import com.lv.dhart.widget.FButton;
import com.lv.dhart.widget.button.CountdownButton;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

public class LoginActivity extends BaseActivity implements ISMSCodeCallback, ILoginCallback {

    RxPermissions rxPermissions;
    String phone;
    String msgCode;
    private LoginViewModel loginViewModel;
    private ActivityLoginBinding binding;
    private CountdownButton msgCodeBtn;
    private LoginPresenter loginPresenter = new LoginPresenter();
    private EditText usernameEditText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory()).get(LoginViewModel.class);

        usernameEditText = binding.username;
        final EditText msgCodeEt = binding.msgCodeEt;
        final FButton loginButton = binding.loginBtn;
        msgCodeBtn = binding.msgCodeBtn;
//        final FButton msgCodeBtn = binding.msgCodeBtn;
        loginViewModel.getLoginFormState().observe(this, loginFormState -> {
            if (loginFormState == null) {
                return;
            }
            loginButton.setEnabled(loginFormState.isDataValid());
            if (loginFormState.getUsernameError() != null) {
                usernameEditText.setError(getString(loginFormState.getUsernameError()));
            }
            if (loginFormState.getPasswordError() != null) {
                msgCodeEt.setError(getString(loginFormState.getPasswordError()));
            }
        });

        loginViewModel.getLoginResult().observe(this, loginResult -> {
            if (loginResult == null) {
                return;
            }
            if (loginResult.getError() != null) {
                showLoginFailed(loginResult.getError());
            }
            if (loginResult.getSuccess() != null) {
                updateUiWithUser(loginResult.getSuccess());
            }
            setResult(Activity.RESULT_OK);

            //Complete and destroy login activity once successful
//                finish();
        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(), msgCodeEt.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        msgCodeEt.addTextChangedListener(afterTextChangedListener);
        msgCodeEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    loginViewModel.login(usernameEditText.getText().toString(), msgCodeEt.getText().toString());
                }
                return false;
            }
        });
        msgCodeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phone = usernameEditText.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    showToast("请输入信息 phone！");
                    return;
                }
                msgCodeBtn.start();
                generateMsgCode();
            }
        });

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgCode = msgCodeEt.getText().toString();
                if (TextUtils.isEmpty(msgCode)) {
                    showToast("请输入信息 msgCode！");
                    return;
                }
                loginH5();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    private void generateMsgCode() {
        phone = usernameEditText.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            showToast("请输入信息 phone！");
            return;
        }
        loginPresenter.loginSmsCode(phone, this);


    }

    private void loginH5() {
        phone = usernameEditText.getText().toString();
        HashMap<String, String> params = new HashMap<>();
        params.put("phone", phone);
        params.put("code", msgCode);
        loginPresenter.login(params, this);
    }

    private void updateUiWithUser(LoggedInUserView model) {
        String welcome = getString(R.string.welcome) + model.getDisplayName();
        // TODO : initiate successful logged in experience
        Toast.makeText(getApplicationContext(), welcome, Toast.LENGTH_LONG).show();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("CheckResult")
    public void getPermissions(final String name, final String pass) {
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(@NonNull Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            //Toast.makeText(LoginActivity.this, "权限获取成功", Toast.LENGTH_SHORT).show();
                            onLogin(name, pass);
                        } else {
                            showMissingPermissionDialog();
                        }
                    }
                });
    }

    /**
     * 用登录举例
     */
    public void onLogin(final String name, final String pass) {
        IProgressDialog mProgressDialog = new IProgressDialog() {
            @Override
            public Dialog getDialog() {
                ProgressDialog dialog = new ProgressDialog(LoginActivity.this);
                dialog.setMessage("登录中...");
                return dialog;
            }
        };
        EasyHttp.post(ComParamContact.Login.PATH).params(ComParamContact.Login.ACCOUNT, name).params(ComParamContact.Login.PASSWORD, MD5.encrypt4login(pass, AppConstant.APP_SECRET)).sign(true).timeStamp(true).execute(new ProgressDialogCallBack<AuthModel>(mProgressDialog, true, true) {
            @Override
            public void onError(ApiException e) {
                super.onError(e);
                showToast("登录失败！" + e.getMessage());
            }

            @Override
            public void onSuccess(AuthModel authModel) {
                showToast("登录成功！");
                //授权类信息存入缓存
                TokenManager.getInstance().setAuthModel(authModel);
                //将用户和密码存入缓存
                LoginCache.getInstance().save(name, pass);
                //Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                //startActivity(intent);
                finish();
            }
        });
    }

    // 显示缺失权限提示
    public void showMissingPermissionDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
        builder.setTitle(R.string.basic_help);
        builder.setMessage(R.string.basic_string_help_text);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.basic_quit, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        builder.setPositiveButton(R.string.basic_settings, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.setCancelable(false);

        builder.show();
    }

    @Override
    public void onSMSCodeSuccess(LoginSendCodeBean loginSendCodeBean) {
        ToastUtils.showLong(String.valueOf(loginSendCodeBean.getTitle().getCode()));
    }

    @Override
    public void onSMSCodeError(Throwable throwable) {

    }

    @Override
    public void onLoginSuccess(LoginBean loginH5SuccessBean) {
        if (loginH5SuccessBean == null) {
            ToastUtils.showLong("服务器出错");
            return;
        }
        if (loginH5SuccessBean.getData() == null) {
            ToastUtils.showLong(loginH5SuccessBean.getMsg());
            return;
        }
        String token = loginH5SuccessBean.getData().getAccessToken().getToken();
        AuthModel authModel = new AuthModel();
        authModel.setAccessToken(token);
        TokenManager.getInstance().setAuthModel(authModel);
        SPStaticUtils.put(AppConstant.APP_TOKEN_KEY, token);
        Intent intent = new Intent(appCompatActivity, BottomBarActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    public void onLoginError(Throwable throwable) {

    }
}